# import sys
import time
from wxauto import *
# from MySQLPool import *
from Config import *
import argparse
# from autoReply import WechatUserMapper
# from autoReply import SysUserMapper
# from autoReply import WechatReceiveObjectMapper
# from autoReply import WechatReceiveMessageMapper

# 连接数据库
def receive_listen_session_new_msgs(listen_session, msg):
    print(listen_session+"新消息:\n"+"类型["+msg.type+"], 发送者["+msg.sender+"], 内容["+msg.content+"]\n")


def receive_listen_session_auto_reply(wx,listen_session, reply_msg):
    # print(listen_session+"自动回复:"+reply_msg+"\n")
    wx.SendMsg(reply_msg, listen_session)


def receive_listen_session_current_msgs(session, msg, receive_object_name_id_map, wechat_user):
    # receive_object_message={
    #     "RECEIVE_OBJECT_ID": receive_object_name_id_map.get(session),
    #     "MESSAGE_SENDER_NUMBER": None,
    #     "MESSAGE_SENDER_NAME": session,
    #     "MESSAGE_RECEIVER_NUMBER": None,
    #     "MESSAGE_RECEIVER_NAME": wechat_user.WECHAT_NAME,
    #     "MESSAGE": msg.content,
    #     "FILE_URL": None,
    #     "SEND_TIME": None,
    #     "CREATE_USER": AUTO_REPLY_USER_NAME,
    #     "CREATE_TIME": time.time(),
    #     "UPDATE_USER": AUTO_REPLY_USER_NAME,
    #     "UPDATE_TIME": time.time()
    # }
    print(session+"类型["+msg.type+"], 发送者["+msg.sender+"], 内容["+msg.content+"]\n")
    # return WechatReceiveMessageMapper.insert(receive_object_message)


def hasNewDragonMsg(wx, listen_session, last_dragon_msg_content, keyword):
    new_dragon_msg=None
    new_dragon_msgs=wx.GetListenMessage(listen_session)
    for msg in new_dragon_msgs:
        if msg is not None and msgHasAllKeyword(msg.content, keyword):
            new_dragon_msg=msg
    return new_dragon_msg


def msgHasAllKeyword(msgContent,keyword):
    keywordSplit = keyword.split("|")
    keywordSpliti = 0
    while (keywordSpliti < len(keywordSplit) - 1):
        if keywordSplit[keywordSpliti] not in msgContent:
            return False
        keywordSpliti += 1
    return True

def combineReplyMsg(last_dragon_msg,auto_reply_msg_num_list,auto_reply_msg):
    # print(time.time_ns())
    # 获取最后一个接龙数字z
    msg_split = last_dragon_msg.content.split("\n")
    msg_last_number = msg_split[len(msg_split) - 1].split(".")[0]
    # 组装接龙消息
    reply_msg = last_dragon_msg.content
    name_number = 1
    for name in auto_reply_msg_num_list:
        msg_last_number = str(int(msg_last_number) + 1)
        reply_msg = reply_msg + "\n" + msg_last_number + ". " + auto_reply_msg + " " + str(
            name_number)
        name_number += 1
    # print(time.time_ns())
    return reply_msg

def main():
    # 创建解析器
    parser = argparse.ArgumentParser(description="自动接龙参数解析")
    # 添加位置参数
    # parser.add_argument("input_file", help="输入文件路径")
    # 添加可选参数（带短选项和长选项）
    # parser.add_argument("-o", "--output", help="输出文件路径")
    # parser.add_argument("-n", "--number", type=int, default=10, help="数量（整数）")
    # parser.add_argument("-v", "--verbose", action="store_true", help="启用详细模式")
    parser.add_argument("-k", "--keywords", help="自动接龙监听的关键字，0：#接龙|1，4：#接龙|周四|1+周四|报名|18人|1，6：#接龙|周六|1，7：#接龙|周日|1+周日|报名|18人|1，10：#Group|1")
    parser.add_argument("-s", "--sessions", help="自动接龙监听的群聊，1：🏐宣晨（曙光店），2：包场小分队，3：昆明乐聚排球综合娱乐群，4：昆明OV周六晚财大风雨馆")
    parser.add_argument("-n", "--numbers", type=int, help="自动接龙的次数")
    # 解析参数
    args = parser.parse_args()

    # 自动接龙监听的关键字
    # args.keywords=4
    if args.keywords is not None:
        dictKeyword=getListenSessionKeywordsDict(args.keywords)
        dictKeywordSplit=dictKeyword.split("+")
        newKeywords=[]
        for keyword in dictKeywordSplit:
            newKeywords.append(keyword)
        setListenSessionKeywords(newKeywords)
        print("监听关键字为:")
        print(getListenSessionKeywords())
    else:
        print("监听关键字为:")
        print(getListenSessionKeywords())

    # 自动接龙监听的群聊
    if args.sessions is not None:
        dictSession = getListenSessionDict(args.sessions)
        setListenSessionList(0,dictSession)
        print("监听的群聊为:")
        print(getListenSessionList()[0])
    else:
        print("监听的群聊为:")
        print(getListenSessionList()[0])

    # 自动接龙的次数
    if args.numbers is not None:
        replyList = []
        for i in range(args.numbers):
            if i==0:
                msg = getAutoReplyMsg()
            else:
                msg=getAutoReplyMsg()+str(i)
            replyList.append(msg)
        setAutoReplyMsgNumList(replyList)
        print("自动接龙次数为:")
        print(str(len(getAutoReplyMsgNumList())))
    else:
        print("自动接龙次数为:")
        print(str(len(getAutoReplyMsgNumList())))

    try:
        # ----------------1.初始化监听对象、自动回复次数、自动回复消息内容、监听对象的监听关键字---------------
        # 1.1获取当前微信客户端
        wx = WeChat("cn")
        # 获取数据库微信用户，没有就保存
        wechatUser=None
        # wechatUser=getDatabaseWechatUserOrSave(wx)
        print("程序已启动，按下 Ctrl + C 可停止运行。")
        # 1.2获取监听对象
        # receive_object_list=WechatReceiveObjectMapper.queryByWechatUserId(wechatUser.ID)
        receive_object_name_id_map={}
        # listen_sessions=[]
        # for receive_object in receive_object_list:
        #     listen_sessions.append(receive_object.OBJECT_NAME)
        #     receive_object_name_id_map.setdefault(receive_object.OBJECT_NAME,receive_object.ID)
        listen_sessions = getListenSessionList()

        # 监听对象当前聊天记录
        listen_session_current_msgs_map={}
        # 1.3添加监听
        for session in listen_sessions:
            # 获取当前聊天记录
            # wx.ChatWith(session)
            # current_msgs=wx.GetAllMessage()
            # listen_session_current_msgs_map.setdefault(session,current_msgs)
            # for msg in current_msgs:
            #     receive_listen_session_current_msgs(session,msg,receive_object_name_id_map,wechatUser)
            # 添加监听，会把会话单独提出来
            wx.AddListenChat(session)

        print("开启监听对象并自动回复:")
        # 监听对象对应的窗口map
        listen_session_chat_wnd_map=wx.GetAllListenChat()

        # 1.4自动回复消息内容
        auto_reply_msg = AUTO_REPLY_MSG
        # 自动回复消息内容列表（接龙的次数）
        auto_reply_msg_num_list = getAutoReplyMsgNumList()

        # 1.5监听关键字
        # 监听对象自动回复次数map
        listen_session_auto_reply_num_map = {}
        listen_session_keywords=getListenSessionKeywords()
        for session in listen_sessions:
            for keyword in listen_session_keywords:
                keywordSplit=keyword.split("|")
                replyNum=keywordSplit[len(keywordSplit)-1]
                if listen_session_auto_reply_num_map.get(session) is None:
                    listen_session_auto_reply_num_map.setdefault(session, {keyword:replyNum})
                else:
                    listen_session_auto_reply_num_map.get(session).setdefault(keyword,replyNum)

        #-----------------2.开始监听对象并自动回复---------------------
        while True:
            # 休眠一段时间再操作
            # time.sleep(5)

            # 1先切换到监听对象，再获取当前所有聊天记录
            # # 获取监听对象的聊天记录
            # for session in listen_sessions:
            #     # 先切换到监听对象聊天框
            #     wx.ChatWith(session)
            #     # 获取监听对象的当前所有聊天记录，以监听对象名称（群聊名/备注名）作为键存入map中
            #     listen_session_msgs_map.setdefault(session, wx.GetAllMessage())
            # 2直接获取监听对象的最新消息
            # print("开始获取监听窗口消息："+str(time.time()))
            listen_session_msgs_map=wx.GetListenMessage()

            # 对所有监听对象的聊天记录进行判断，如果有接龙，则自动接龙
            # print("判断聊天记录开始")
            for listen_session in listen_sessions:
                # print("判断"+listen_session+"聊天记录")
                # 监听对象对应的窗口
                chat_wnd=listen_session_chat_wnd_map.get(listen_session)
                # 获取监听对象的新消息
                new_msgs=listen_session_msgs_map.get(chat_wnd)
                # 有接龙消息的栈，只接最后一次
                dragon_msg_stack = {}
                for keyword in listen_session_keywords:
                    dragon_msg_stack.setdefault(keyword,[])
                # 对每一条新消息判断是否有接龙
                if new_msgs is not None:
                    for msg in new_msgs:
                        # 打印或输出到文件中或存入数据库
                        receive_listen_session_new_msgs(listen_session, msg)
                        # 如果非自身发的消息有当前监听对象的监听关键字（接龙）
                        if msg.type != TIME_MSG:
                            for keyword in listen_session_keywords:
                                if msgHasAllKeyword(msg.content,keyword):
                                    dragon_msg_stack.get(keyword).append(msg)

                # 如果当前监听对象有接龙消息并且自动接龙次数>0，则自动接龙，自动接龙次数-1
                # print("判断每个关键字是否需要接龙")
                for keyword in listen_session_keywords:
                    # print("判断"+keyword+"关键字是否需要接龙")
                    stack=dragon_msg_stack.get(keyword)
                    num=int(listen_session_auto_reply_num_map.get(listen_session).get(keyword))
                    if len(stack)>0 and num >0:
                        # 如果有一个关键字可以接龙了，其他关键字的接龙次数就清零
                        sessionNumDict=dict(listen_session_auto_reply_num_map.get(listen_session))
                        for key, value in sessionNumDict.items():
                            if key!=keyword:
                                listen_session_auto_reply_num_map.get(listen_session).update({key: 0})

                        last_dragon_msg=stack.pop()
                        # 组装自动接龙消息
                        reply_msg=combineReplyMsg(last_dragon_msg,auto_reply_msg_num_list,auto_reply_msg)
                        # 发送前判断是否有新接龙消息
                        # isRecombineReplyMsg=False
                        time.sleep(HUMAN_EDIT_TIME)
                        # while True:
                        #     # print("判断是否有新接龙消息："+str(time.time()))
                        #     new_dragon_msg=hasNewDragonMsg(wx,listen_session,last_dragon_msg.content,keyword)
                        #     if new_dragon_msg is None:
                        #         break
                        #     last_dragon_msg=new_dragon_msg
                        #     isRecombineReplyMsg=True
                        # # 如果有新消息，就重组
                        # if isRecombineReplyMsg:
                        #     reply_msg=combineReplyMsg(last_dragon_msg,auto_reply_msg_num_list,auto_reply_msg)
                        print("准备发送接龙消息："+str(time.time()))
                        receive_listen_session_auto_reply(wx, listen_session, reply_msg)
                        print("发送完毕："+str(time.time()))
                        # 自动回复次数-1
                        listen_session_auto_reply_num_map.get(listen_session).update({keyword:num-1})
    except (KeyboardInterrupt, SystemExit):
        print("程序已停止！")
        sys.exit(0)


# def getDatabaseWechatUserOrSave(wx_client):
#     wechatUser = WechatUserMapper.queryByWechatName(wx_client.nickname)
#     if wechatUser is None:
#         sysUser = SysUserMapper.queryByUsername(AUTO_REPLY_USER_NAME)
#         if sysUser is None:
#             print(AUTO_REPLY_USER_NAME + "用户不存在")
#             sys.exit(0)
#         # 添加微信用户
#         wechatUser = {
#             "SYS_USER_ID": sysUser.id,
#             "WECHAT_NUMBER": "",
#             "WECHAT_NAME": wx_client.nickname,
#             "WECHAT_CREDENTIAL": "",
#             "CREATE_USER": AUTO_REPLY_USER_NAME,
#             "CREATE_TIME": time.time(),
#             "UPDATE_USER": AUTO_REPLY_USER_NAME,
#             "UPDATE_TIME": time.time(),
#         }
#         insertSuc=False
#         insertNum = 10
#         while insertNum >0:
#             rows_affected = WechatUserMapper.insert(wechatUser)
#             if rows_affected > 0:
#                 insertSuc=True
#                 break;
#             insertNum-=1;
#         if insertSuc:
#             wechatUser=WechatUserMapper.queryByWechatName(wx_client.nickname)
#         else:
#             print("数据库插入微信用户失败，请检查网络或数据库并重新启动")
#             sys.exit(0)
#     return wechatUser


if __name__ == "__main__":
    main()